package models

import (
	"context"
	"fmt"
	"time"
	_ "time"

	"go-papers/cache"
	orm "go-papers/database"
	"go-papers/pkg/lognew"
	"go-papers/tools"
)

type MemberPosition struct {
	Id             int    `json:"id" gorm:"type:int(11);primary_key"`       //
	MemberId       int    `json:"memberId" gorm:"type:int(11);"`            // 用户id
	MemberWt       string `json:"memberWt" gorm:"type:varchar(255);"`       // 用户维度 lat代表纬度
	MemberLt       string `json:"memberLt" gorm:"type:varchar(255);"`       // 用户经度 lng代表经度
	OpenId         string `json:"openId" gorm:"type:varchar(255);"`         // 用户微信openId
	MemberPosition string `json:"memberPosition" gorm:"type:varchar(255);"` // 用户位置

	DataScope string `json:"dataScope" gorm:"-"`
	Params    string `json:"params"  gorm:"-"`
	BaseModel
}

type MemberPositionPost struct {
	MemberWt string `json:"memberWt"  ` // 用户维度 lat代表纬度
	MemberLt string `json:"memberLt"  ` // 用户经度 lng代表经度
	OpenId   string `json:"openId"  `   // 用户微信openId
}

func (MemberPosition) TableName() string {
	return "member_position"
}

// 创建MemberPosition
func (e *MemberPosition) Create() (MemberPosition, error) {
	var doc MemberPosition
	result := orm.Eloquent.Table(e.TableName()).Create(&e)
	if result.Error != nil {
		err := result.Error
		return doc, err
	}
	doc = *e
	return doc, nil
}

// GetOrgansArr
func (e *MemberPosition) GetOrgansArr(distance float64, start float64) []int {
	var out []int
	pp, _ := e.GetByIdOrOpenId(e.MemberId, e.OpenId)
	if pp.Id <= 0 {
		return out
	}

	//根据距离查询 机构列表
	var organ Organ
	list, err := organ.GetListByPosition(pp.MemberLt, pp.MemberWt, distance, start)
	if err != nil {
		lognew.Error(context.TODO(), "GetListByPosition", lognew.Fields{"pp": pp, "start": start, "end": distance, "err": err.Error()})
		return out
	}
	if len(list) > 0 {
		for _, v := range list {
			out = append(out, v.OrganId)
		}
	}
	return out
}

func (e *MemberPosition) GetOrgansArrV2(distance float64, start float64) []OrganPPList {
	var out []OrganPPList
	pp, _ := e.GetByIdOrOpenId(e.MemberId, e.OpenId)
	if pp.Id <= 0 {
		return out
	}

	//根据距离查询 机构列表
	var organ Organ
	list, err := organ.GetListByPosition(pp.MemberLt, pp.MemberWt, distance, start)
	if err != nil {
		lognew.Error(context.TODO(), "GetListByPosition", lognew.Fields{"pp": pp, "start": start, "end": distance, "err": err.Error()})
		return out
	}
	return list
}

func (e *MemberPosition) GetByIdOrOpenId(mid int, openId string) (MemberPosition, error) {
	var doc MemberPosition

	// cache 获取
	cacheKey := fmt.Sprintf("location:%s", openId)
	if mid > 0 {
		cacheKey = fmt.Sprintf("location:%d", mid)
	}
	if foo, ok := cache.GoLocalCache.Get(cacheKey); ok {
		l, _ := foo.(MemberPosition)
		return l, nil
	}

	table := orm.Eloquent.Table(e.TableName())
	if e.Id != 0 {
		table = table.Where("id = ?", e.Id)
	}
	if mid > 0 {
		table = table.Where("member_id = ?", mid)
	} else if openId != "" {
		table = table.Where("open_id = ?", openId)
	} else {
		return doc, nil
	}

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}

	// 写入cache
	cache.GoLocalCache.Set(cacheKey, doc, 5*time.Minute)

	return doc, nil
}

// 获取MemberPosition
func (e *MemberPosition) Get() (MemberPosition, error) {
	var doc MemberPosition
	table := orm.Eloquent.Table(e.TableName())
	if e.Id != 0 {
		table = table.Where("id = ?", e.Id)
	}
	if e.MemberId > 0 {
		table = table.Where("member_id = ?", e.MemberId)
	}
	if e.OpenId != "" {
		table = table.Where("open_id = ?", e.OpenId)
	}
	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// 获取MemberPosition带分页
func (e *MemberPosition) GetPage(pageSize int, pageIndex int) ([]MemberPosition, int, error) {
	var doc []MemberPosition

	table := orm.Eloquent.Select("*").Table(e.TableName())
	if e.Id != 0 {
		table = table.Where("id = ?", e.Id)
	}
	if e.MemberId != 0 {
		table = table.Where("member_id = ?", e.MemberId)
	}
	if e.OpenId != "" {
		table = table.Where("open_id = ?", e.OpenId)
	}
	if e.MemberPosition != "" {
		table = table.Where("member_position = ?", e.MemberPosition)
	}

	// 数据权限控制(如果不需要数据权限请将此处去掉)
	dataPermission := new(DataPermission)
	dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
	table, err := dataPermission.GetDataScope(e.TableName(), table)
	if err != nil {
		return nil, 0, err
	}
	var count int

	if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("`deleted_at` IS NULL").Count(&count)
	return doc, count, nil
}

// 更新MemberPosition
func (e *MemberPosition) Update(id int) (update MemberPosition, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
		return
	}

	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
		return
	}
	return
}

// 删除MemberPosition
func (e *MemberPosition) Delete(id int) (success bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&MemberPosition{}).Error; err != nil {
		success = false
		return
	}
	success = true
	return
}

//批量删除
func (e *MemberPosition) BatchDelete(id []int) (Result bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&MemberPosition{}).Error; err != nil {
		return
	}
	Result = true
	return
}
